package xyz.lovegu.server.sys.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.lovegu.server.sys.common.ActiverUser;
import xyz.lovegu.server.sys.common.ResultObj;
import xyz.lovegu.server.sys.common.WebUtils;
import xyz.lovegu.server.sys.dos.Loginfo;
import xyz.lovegu.server.sys.mapper.LoginfoMapper;
import xyz.lovegu.server.sys.service.LoginfoService;
import xyz.lovegu.server.sys.vos.UserVo;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @author 老顾
 * @title: LoginfoServiceImpl
 * @projectName campus-prevention-system
 * @email: 1437594522@qq.com
 * @date 2022/5/5 21:22
 */
@RequiredArgsConstructor
@Service
@Transactional
public class LoginfoServiceImpl extends ServiceImpl<LoginfoMapper, Loginfo> implements LoginfoService {


    @Override
    public ResultObj userLogin(UserVo userVo, HttpSession session) {
        //获得存储在session中的验证码
       // String sessionCode = (String) session.getAttribute("code");
        //if (code!=null&&sessionCode.equals(code)){
            /*Subject subject = SecurityUtils.getSubject();*/
            new UsernamePasswordToken(userVo.getLoginName(),userVo.getPassword());
            try {
                /*对用户进行认证登陆
                subject.login(token);*/
                ActiverUser activerUser = new ActiverUser();
                //将user存储到session中
                WebUtils.getSession().setAttribute("user",activerUser.getUser());
                //记录登陆日志
                Loginfo entity = new Loginfo();
                entity.setLoginName(userVo.getLoginName());
                entity.setLoginIp(WebUtils.getRequest().getRemoteAddr());
                entity.setLoginTime(new Date());
                this.save(entity);
                return ResultObj.LOGIN_SUCCESS;
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return ResultObj.LOGIN_ERROR_PASS;
            }
        //}else {
          //  return ResultObj.LOGIN_ERROR_CODE;
        //}

    }

    @Override
    public void getCode(HttpServletResponse response, HttpSession session) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116, 36,4,5);
        session.setAttribute("code",lineCaptcha.getCode());
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
